package com.xiaou.es.demo;

import java.net.InetAddress;
import java.net.UnknownHostException;

import org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.cluster.health.ClusterHealthStatus;
import org.elasticsearch.cluster.health.ClusterIndexHealth;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.Log4J2LoggerFactory;

/**
 * 了解集群健康状况
 * @author xiaou
 * @date 2018年9月15日-下午2:55:32
 */
public class ClusterDemo {
	private TransportClient client;
	private static InternalLogger log =Log4J2LoggerFactory.getInstance(EasyCrud.class);
	
	@SuppressWarnings("resource")
	@Before
	public void before() throws UnknownHostException {
		
		Settings settings = Settings.builder()
				.put("cluster.name", "myes")
				.build();
		client = new PreBuiltTransportClient(settings)
				.addTransportAddress(
						new TransportAddress(InetAddress.getByName("192.168.150.142"), 9300)
						);
	}
	
	@After
	public void after() {
		client.close();
	}
	
	//查看集群的健康状况
	@Test
	public void test1() {
		ClusterHealthResponse healths = client.admin().cluster().prepareHealth().get();
		
		String clusterName = healths.getClusterName();
		log.info("集群名字:"+clusterName);
		
		// 获得数据节点数量
		int numberOfDataNodes = healths.getNumberOfDataNodes();
		log.info("数据节点数量:"+numberOfDataNodes);
		// 获得节点总数量
		int numberOfNodes = healths.getNumberOfNodes();
		log.info("节点的总数量:"+numberOfNodes);
		//索引的健康状态
		for(ClusterIndexHealth health : healths.getIndices().values()) {
			String 	index = health.getIndex();
			int numberOfShards = health.getNumberOfShards();//分片
			int numberOfReplicas = health.getNumberOfReplicas();//副本
			log.info("index="+index+"    numberOfShards="+numberOfShards+"   numberOfReplicas="+numberOfReplicas);
			ClusterHealthStatus status = health.getStatus();
			log.info("索引的健康值    "+ status);
		}
	}
	
}
